package com.example.api.service.impl;

import com.example.api.dao.CompanyDao;
import com.example.api.dao.PurchaseDao;
import com.example.api.dao.SaleDao;
import com.example.api.model.constants.LogisticsConstants;
import com.example.api.model.entity.Company;
import com.example.api.model.entity.Purchase;
import com.example.api.model.entity.Sale;
import com.example.api.model.support.RespBean;
import com.example.api.service.SaleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class SaleServiceImpl implements SaleService {

    @Resource
    private SaleDao saleDao;

    @Resource
    private CompanyDao companyDao;

    @Resource
    private PurchaseDao purchaseDao;

    @Override
    public RespBean save(Sale sale) {
        sale.setArrival(LogisticsConstants.SALE_ARRIVAL_1);
        sale.setCreateTime(new Date());
        if (saleDao.insertSelective(sale) > 0) {
            Company company = companyDao.selectByCompany(sale.getCompany().trim());
            if (Objects.isNull(company)) {
                Company newCompany = new Company();
                newCompany.setName(sale.getCompany());
                newCompany.setPhone(sale.getPhone());
                newCompany.setCreateTime(sale.getCreateTime());
                companyDao.insertSelective(newCompany);
            }
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @Override
    public List<Sale> findAll(String name) {
        return saleDao.findAll(name);
    }

    @Override
    public RespBean update(Sale sale) {
        sale.setArrival(LogisticsConstants.SALE_ARRIVAL_0);
        if (saleDao.updateByPrimaryKeySelective(sale) > 0) {
            Purchase purchase = new Purchase();
            purchase.setSid(sale.getId());
            purchase.setCid(sale.getCommodity());
            purchase.setCount(sale.getCount());
            purchase.setCreateTime(new Date());
            purchaseDao.insertSelective(purchase);
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

}